import {base} from 'nc-lightapp-front';

const {NCCheckbox} = base;
let materialength = 0;
let billid0;
let ctrt_meta = {};
export default class FormAction {
    constructor(comp) {
        this.comp = comp;
    }

    // 表单进入编辑态,待入职
    toEditStatus = (formValue) => {
        const {props, action} = this.comp;
        const {form, dispatch, button, editTable, meta, emp} = props;
        if (formValue.material) {
            materialength = formValue.material.material.rows.length;
        }
        //设置入职材料列表checkbox显示
        let template = meta.getMeta();
        template = this.initMetaEdit(template);
        template['hi_psndoc_ctrt'] = formValue.ctrt_meta;
        template['hi_psndoc_ctrt'].items.find((item) => item.attrcode === 'pk_conttext').queryCondition = function () {
            return {
                pk_org: emp.orgValue.refpk,
                GridRefActionExt: 'nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder'
            };
        };
        meta.setMeta(template);
        form.setFormItemsRequired('card', {psncode: true});
        for (let i = 0; i < formValue.ctrt_meta.items.length; i++) {
            let code = formValue.ctrt_meta.items[i].attrcode;
            form.setFormItemsDisabled('hi_psndoc_ctrt', {
                [code]: formValue.ctrt_meta.items[i].disabled
            });
        }
        //meta.setMeta(formValue.ctrt_meta)
        // 表单进入编辑
        form.setFormStatus('card', 'edit');
        editTable.setStatus('material', 'edit');
        form.setFormStatus('hi_psndoc_ctrt', 'edit');

        // 填充表单的值
        if (formValue) {
            if (formValue.card) {
                form.setAllFormValue({
                    card: formValue.card.card
                });
            }
            form.setFormItemsDisabled('card', {
                psncode: !formValue.isPsncodEditable,
            });
            form.setFormItemsDisabled('hi_psndoc_ctrt', {
                contractnum: !formValue.isCtrtEditable
            })
            if (formValue.material) {
                editTable.setTableData('material', formValue.material.material, false);
                for (let i = 0; i < editTable.getNumberOfRows('material'); i++) {
                    editTable.setEditableRowKeyByIndex('material', i, 'pk_material', false);
                    editTable.setEditableRowKeyByIndex('material', i, 'receivedate', false);
                }
                //editTable.setColEditableByKey('material', 'receivedate', true)
                //dispatch是异步的，update后不会马上更新emp中的值
            }
            if (formValue.hi_psndoc_ctrt) {
                form.setAllFormValue({
                    hi_psndoc_ctrt: formValue.hi_psndoc_ctrt.hi_psndoc_ctrt
                });
            }
        }
    };

    btnInEdit = (formValue) => {
        const {props, action} = this.comp;
        const {form, dispatch, button, editTable, meta, emp} = props;
        // 按钮进入编辑的按钮
        if (formValue.hi_psndoc_ctrt.hi_psndoc_ctrt.rows[0].values.pk_psndoc_sub.value && formValue.showCtrt) {
            //合同表单是否必填

            dispatch({
                type: 'emp/update',
                payload: {
                    addPageStatus: 'edit',
                    isUnentryEdit: true,
                    ctrtBtnDisp: 'none', //gaihaole!!!@@@@@
                    ctrtOpenBtnDisp: 'none',
                    ctrtDisp: 'inline'
                }
            });
        } else {
            if (formValue.showCtrt) {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        addPageStatus: 'edit',
                        isUnentryEdit: true,
                        ctrtBtnDisp: 'inline',
                        ctrtOpenBtnDisp: 'none',
                        ctrtDisp: 'inline'
                    }
                });
            } else {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        addPageStatus: 'edit',
                        isUnentryEdit: true,
                        ctrtBtnDisp: 'none',
                        ctrtOpenBtnDisp: 'inline',
                        ctrtDisp: 'none'
                    }
                });
            }
        }
        //设置表单、表格编辑态
        editTable.setColEditableByKey('material', 'receivedate', false);
        // 隐藏掉一些按钮
        button.setButtonVisible({
            refresh: false,
            handentry: true,
            save: true,
            qryentry: true,
            psninfo: true,
            query: false,
            print: true
        });
    };

    // 进入待入职页面
    toEditPage = async (selectedRows) => {
        const {props} = this.comp;
        const {dispatch} = props;
        billid0 = selectedRows[0].values['pk_entryapply'].value;
        try {
            let oneBillData = await this.getOneBillData(selectedRows);
            if (oneBillData) {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        page: 'edit'
                    }
                });
            }
            this.toEditStatus(oneBillData.data);
            this.btnInEdit(oneBillData.data);
        } catch (e) {
        }
    };

    // 获取一条数据
    getOneBillData = async (selectedRows) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp} = props;

        let postData = {
            billid: selectedRows[0].values['pk_entryapply'].value,
            pk_org: emp.orgValue.refpk
        };

        try {
            let res = await dispatch({
                type: 'emp/getOneBillData',
                payload: {
                    postData: postData
                }
            });

            if (res.success) {
                return res;
            }
        } catch (e) {
            return false;
        }

        return true;
    };

    // 直接进入已入职页面
    toBrowsePage = async (selectedRows, formValue) => {
        const {props} = this.comp;
        const {dispatch, button, emp} = props;

        if (formValue) {
            this.toBrowseStatus(formValue);
            return;
        }
        //try {
        let oneBillData = await this.getOneBillData(selectedRows);

        dispatch({
            type: 'emp/update',
            payload: {
                page: 'browse'
            }
        });
        button.setButtonVisible({
            refresh: false,
            save: false
        });
        this.toBrowseStatus(oneBillData.data);
        this.btnInBrowse();
        //} catch (e) {}
    };

    // 表单进入浏览态,已入职
    toBrowseStatus = (formValue) => {
        const {props} = this.comp;
        const {form, editTable, meta} = props;
        //设置入职材料列表checkbox隐藏
        let template2 = meta.getMeta();
        template2 = this.initMetaBrowse(template2);
        meta.setMeta(template2);
        // 表单进入浏览
        form.setFormStatus('card', 'browse');
        form.setFormStatus('hi_psndoc_ctrt', 'browse');
        editTable.setStatus('material', 'browse');
        // 填充表单的值
        if (!formValue) return;
        form.setAllFormValue({
            card: formValue.card.card
        });
        editTable.setTableData('material', formValue.material.material, false);
        if (formValue.hi_psndoc_ctrt) {
            form.setAllFormValue({
                hi_psndoc_ctrt: formValue.hi_psndoc_ctrt.hi_psndoc_ctrt
            });
        }

        form.setFormItemsDisabled('card', {
            psncode: !formValue.isPsncodEditable
        });
        form.setFormItemsDisabled('hi_psndoc_ctrt', {
            contractnum: !formValue.isCtrtEditable
        })
    };

    btnInBrowse = () => {
        const {props, action} = this.comp;
        const {form, dispatch, button, editTable, meta} = props;
        // 按钮进入浏览（隐藏保存按钮的编辑态）
        dispatch({
            type: 'emp/update',
            payload: {
                addPageStatus: 'browse',
                isUnentryEdit: false,
                ctrtBtnDisp: 'none',
                ctrtOpenBtnDisp: 'none',
                ctrtDisp: 'inline'
            }
        });
        // 隐藏掉一些按钮
        button.setButtonVisible({
            refresh: false,
            handentry: false,
            save: false,
            qryentry: true,
            psninfo: true,
            query: false,
            print: true
        });
    };

    // 开关表单
    openForm = async () => {
        const {props} = this.comp;
        const {emp, dispatch, form} = props;
        dispatch({
            type: 'emp/update',
            payload: {
                ctrtBtnDisp: 'inline',
                ctrtOpenBtnDisp: 'none',
                ctrtDisp: 'inline'
            }
        });
        let postData = {
            billid: billid0,
            pk_org: emp.orgValue.refpk
        };

        try {
            let res = await dispatch({
                type: 'emp/getOneBillData',
                payload: {
                    postData: postData
                }
            });

            if (res.success) {
                form.setAllFormValue({
                    hi_psndoc_ctrt: res.data.hi_psndoc_ctrt.hi_psndoc_ctrt
                });
            }
        } catch (e) {
            return false;
        }
    };

    // 开关表单
    closeForm = () => {
        const {props, action} = this.comp;
        const {emp, dispatch, form} = props;

        dispatch({
            type: 'emp/update',
            payload: {
                ctrtBtnDisp: 'none',
                ctrtOpenBtnDisp: 'inline',
                ctrtDisp: 'none'
            }
        });
    };

    //进入编辑态配置模板给表格列加checkbox
    initMetaEdit = (template) => {
        const {props} = this.comp;
        const {emp} = props;
        template['material'].items.forEach((item) => {
            if (item.attrcode == 'isreceive') {
                //item.label.props.children[0].props.style={display: 'block-inline'}
                item.tempLable = item.tempLable || item.label;
                item.label = (
                    <div>
						<span style={{display: emp.checkboxDisp}}>
							<NCCheckbox
                                //checked={emp.checkall}
                                onChange={this.onCheckAllChange}
                            />
						</span>
                        <span>{item.tempLable}</span>
                    </div>
                );
            }
        });
        return template;
    };

    //进入浏览态后将表格是否接收列头部的checkbox去掉
    initMetaBrowse = (template) => {
        template['material'].items.forEach((item) => {
            if (item.attrcode == 'isreceive') {
                item.tempLable = item.tempLable || item.label;
                item.label = (
                    <div>
                        <span>{item.tempLable}</span>
                    </div>
                );
            }
        });
        return template;
    };

    //checkbox值改变回调
    onCheckAllChange = (e) => {
        const {props, action} = this.comp;
        const {emp, editTable, meta} = props;
        let nowYear = new Date().getFullYear().toString();
        let nowMonth = (new Date().getMonth() + 1).toString();
        let nowDay = new Date().getDate().toString();

        function timeAdd0(str) {
            if (str.length <= 1) {
                str = '0' + str;
            }
            return str;
        }

        nowYear = timeAdd0(nowYear);
        nowMonth = timeAdd0(nowMonth);
        nowDay = timeAdd0(nowDay);
        let dateString = nowYear + '-' + nowMonth + '-' + nowDay;
        if (e == true) {
            for (let i = 0; i < materialength; i++) {
                if (editTable.getValByKeyAndIndex('material', i, 'uncommit').value == true) {
                    editTable.setValByKeyAndIndex('material', i, 'uncommit', {value: false});
                }
            }
            for (let i = 0; i < materialength; i++) {
                editTable.setValByKeyAndIndex('material', i, 'isreceive', {value: true});
                editTable.setValByKeyAndIndex('material', i, 'receivedate', {
                    value: dateString,
                    display: dateString,
                    scale: '0'
                });
            }
        } else {
            for (let i = 0; i < materialength; i++) {
                editTable.setValByKeyAndIndex('material', i, 'isreceive', {value: false});
                editTable.setValByKeyAndIndex('material', i, 'receivedate', {
                    value: null,
                    display: undefined,
                    scale: '0'
                });
            }
        }
    };
}
